#include "udp.h"
#include "ui_udp.h"

udp::udp(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::udp)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);

}

udp::~udp()
{
    delete ui;
}

void udp::read_udp_data_slot(void)
{
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray read_data;
        read_data.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(read_data.data(), read_data.size());
        QString buf;
        buf = read_data.data();
        ui->plainTextEdit_recvdata->appendPlainText(buf);
    }
}
void udp::on_pushButton_open_clicked()
{
    if(udpSocket->bind(ui->lineEdit_local_port->text().toUInt()) == true)
    {
        QMessageBox::information(this, "提示", "打开成功");
        connect(udpSocket, SIGNAL(readyRead()), this, SLOT(read_udp_data_slot()));
    }
    else
    {
        QMessageBox::information(this, "提示", "打开失败");
    }

}

void udp::on_pushButton_send_data_clicked()
{
    quint16 port;
    QString send_buf;
    QHostAddress addr;

    addr.setAddress(ui->lineEdit_op_ip->text());
    send_buf = ui->lineEdit_send_data->text();
    port = ui->lineEdit_op_port->text().toUInt();

    udpSocket->writeDatagram(send_buf.toLocal8Bit().data(), send_buf.length(), addr, port);
}

void udp::on_pushButton_close_clicked()
{
    udpSocket->close();

}
